"""
    Plugin for converting iTunes Playlist to m3u Playlist
"""
#import rpdb2 
#rpdb2.start_embedded_debugger('pw')

__plugin__ = "iTunes_library_to_m3u"
__author__ = "David Magniez <davidmagniez@free.fr>"

import sys
import os
import os.path
import xbmc
import xbmcgui as gui
import xbmcplugin as plugin
import xbmcaddon


BASE_URL = "%s" % (sys.argv[0])
PLUGIN_PATH = xbmc.translatePath(os.getcwd())
RESOURCE_PATH = os.path.join(PLUGIN_PATH, "resources")
LIB_PATH = os.path.join(RESOURCE_PATH, "lib")
sys.path.append(LIB_PATH)


# path of playlists files for XBMC
m3u_path = xbmc.translatePath('special://profile/playlists/music/')

# root directory of the addon
addon = xbmcaddon.Addon(id=os.path.basename(os.getcwd()))



class Main:

    def __init__(self):
		
		libraryfile = addon.getSetting('library_path')
		otherpath = addon.getSetting('other_path')
		update_scheduled = addon.getSetting('update_scheduled')
		
		if not os.path.isfile(libraryfile):
			xbmc.executebuiltin('XBMC.Notification("Playlist Importer"," "iTunes Library can not be read")')
			sys.exit()

		if (otherpath=="false"):
			musicpath='noreplace'
			oldmusicpath='noreplace'
		else:
			musicpath = addon.getSetting('music_path')
			oldmusicpath = addon.getSetting('oldmusic_path')

		#from resources.lib.plistloader import *
		from resources.lib.xmltom3u import *

		# this part (automatic update) is based on plugin XBMC Library Auto Update, thanks to them !
		if (update_scheduled):
			#cancel the alarm if it is already running
			xbmc.executebuiltin('CancelAlarm(updateplaylist)')

			timer_amounts = {}
			timer_amounts['0'] = '120'
			timer_amounts['1'] = '300'
			timer_amounts['2'] = '600'
			timer_amounts['3'] = '900'
			timer_amounts['4'] = '1440'

			#only do this if we are not playing anything
			if(xbmc.Player().isPlaying() == False):
				number_playlist= itunesconvert(libraryfile,oldmusicpath,musicpath,m3u_path)

			#reset the timer
			xbmc.executebuiltin('AlarmClock(updateplaylist,XBMC.RunScript(script.itunestom3u),' + timer_amounts[addon.getSetting('timer_amount')] +  ',true)')

			xbmc.log('automatic update of playlists complete')
		else:
			number_playlist= itunesconvert(libraryfile,oldmusicpath,musicpath,m3u_path)
			xbmc.executebuiltin('XBMC.Notification("Playlists Updated"," " Playlists are Updated !")')
			xbmc.log('manual update of playlists complete')
#run the program
run_program = Main()

